#include <xconfig.h>
#include <xsocket.h>
#include <xsocketdefine.h>
#if CONFIG_BCB
    #pragma hdrstop
#endif
#include "xsocketstream.h"
namespace zdh
{
	bool XSocketStream::WaitForData(int aTimeout)
	{
		assert(aTimeout>0);
		if( aTimeout < 0 ) aTimeout = 1;
		fd_set fd_read_set;
		timeval tvTimeout;
		tvTimeout.tv_sec = aTimeout/1000;
		tvTimeout.tv_usec = (aTimeout%1000)*1000;
		FD_ZERO(&fd_read_set);
		FD_SET(_P_HANDLE_(m_Socket),&fd_read_set);
		return XSocketAPI::Select(_P_HANDLE_(m_Socket)+1,&fd_read_set,NULL,NULL,&tvTimeout)>0;
	}
	
	int XSocketStream::Read(void * buffer,int aBufferSize)
	{
		if( WaitForData( m_Timeout ) )
		{
			XSSize aRetSize = XSocketAPI::Recv(_P_HANDLE_(m_Socket),(char *)buffer,aBufferSize,0);
			m_ErrorCode = XSocketAPI::GetErrorNo();
			return aRetSize;
		}else m_ErrorCode = XSocketAPI::GetErrorNo();
		return 0;
	}

	int XSocketStream::Write(void * buffer,int aBufferSize)
	{
		XSSize aRetSize = XSocketAPI::Send(_P_HANDLE_(m_Socket),(const char *)buffer,aBufferSize,0);
		m_ErrorCode = XSocketAPI::GetErrorNo();
		return aRetSize;
	}

	void XSocketStream::setTimeout(int aTimeout) 
	{
		assert(aTimeout>0);
		if( aTimeout < 0 ) aTimeout=1;
		m_Timeout = aTimeout;
	}

}
